package com.guimin.order.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guimin.order.constant.GmYuyueOrderConstant;
import com.guimin.order.dto.AddYuyueOrderDto;
import com.guimin.order.entity.GuiminYuyueOrder;
import com.guimin.order.service.GuiminYuyueOrderService;
import com.guimin.site.entity.GuiminSite;
import com.guimin.site.service.GuiminSiteService;
import com.guimin.user.api.UserInfoApi;
import com.guimin.user.constant.UserConstant;
import com.guimin.user.dto.LoginInfoDto;
import com.guimin.user.entity.UserInfo;
import com.guimin.user.service.UserInfoService;
import com.guimin.wuye.entity.GmProperty;
import com.guimin.wuye.service.GmPropertyService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 预约订单表(GuiminYuyueOrder)控制层
 *
 * @author hzy
 * @since 2021-11-25 14:46:06
 */
@RestController
@RequestMapping("guiminYuyueOrder")
public class GuiminYuyueOrderApi {
    /**
     * 服务对象
     */
    @Resource
    private GuiminYuyueOrderService guiminYuyueOrderService;
    @Resource
    private UserInfoApi userInfoApi;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private GuiminSiteService guiminSiteService;
    @Resource
    private GmPropertyService gmPropertyService;

    /**
     * 获取预约订单
     *
     * @return r
     */
    @GetMapping("/all")
    public R<List<GuiminYuyueOrder>> all() {
        List<GuiminYuyueOrder> list = guiminYuyueOrderService.list();
        return R.ok(list);
    }

    /**
     * 获取预约订单
     *
     * @param current 当前页
     * @param size    每页大小
     * @return r
     */
    @GetMapping("/list")
    public R<IPage<GuiminYuyueOrder>> list(HttpServletRequest request,
                                           @RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "10") Integer size) {
        LoginInfoDto login = userInfoApi.getLogin(request);
        //获取用户的预约
        IPage<GuiminYuyueOrder> page = guiminYuyueOrderService.page(new Page<>(current, size),
                new LambdaQueryWrapper<GuiminYuyueOrder>().eq(GuiminYuyueOrder::getUserId, login.getId()).orderByDesc(GuiminYuyueOrder::getId));
        //检查已过时订单
        ArrayList<Integer> ids = new ArrayList<>(page.getRecords().size());
        for (GuiminYuyueOrder item : page.getRecords()) {
            if (item.getState().equals(GmYuyueOrderConstant.State.WAIT_USE.value) && item.getServiceDate().getTime() <= System.currentTimeMillis()) {
                ids.add(item.getId());
                item.setState(GmYuyueOrderConstant.State.OUTMODED.value);
            }
        }
        if (ids.size() > 0) {
            //设置已过时订单
            guiminYuyueOrderService.update(new GuiminYuyueOrder().setState(GmYuyueOrderConstant.State.OUTMODED.value),
                    new LambdaUpdateWrapper<GuiminYuyueOrder>().in(GuiminYuyueOrder::getId, ids));
        }
        return R.ok(page);
    }

    /**
     * 添加预约订单
     *
     * @return r
     */
    @PostMapping("/add")
    public R<Boolean> addAppointment(@RequestBody @Validated AddYuyueOrderDto dto, HttpServletRequest request) {
        LoginInfoDto login = userInfoApi.getLogin(request);
//        根据服务id查找服务所属物业
        GuiminSite service = guiminSiteService.getOne(new LambdaQueryWrapper<GuiminSite>()
                .select(GuiminSite::getServe, GuiminSite::getVillageProperty)
                .eq(GuiminSite::getId, dto.getServiceId()));
        if (service == null) {
            return R.failed("找不到该服务");
        }
//        根据物业名称查找物业id和名称
        GmProperty property = gmPropertyService.getOne(new LambdaQueryWrapper<GmProperty>()
                .select(GmProperty::getId, GmProperty::getName)
                .eq(GmProperty::getName, service.getVillageProperty()));
        if (property == null) {
            return R.failed("服务所属物业错误");
        }
        //保存
        boolean save = guiminYuyueOrderService.save(new GuiminYuyueOrder()
                .setUserId(login.getId())
                .setUserName(dto.getUserName())
                .setPhone(dto.getPhone())
                .setServiceId(dto.getServiceId())
                .setServiceName(dto.getServiceName())
                .setServiceDate(dto.getServiceDate())
                .setServiceSite(dto.getServiceSite())
                .setLoveEnergy(30)
                .setPropertyId(property.getId())
                .setPropertyName(property.getName())
                .setCreateDatetime(new Date())
                .setState(GmYuyueOrderConstant.State.WAIT_USE.value)
                .setVerifyCode(String.format("%04d", new Random().nextInt(9999))));
        return save ? R.ok(null) : R.failed("添加失败");
    }


    /**
     * 获取待使用的预约
     *
     * @param verifyCode 核销码
     * @return r
     */
    @PutMapping("/get/order/by/code")
    public R<List<GuiminYuyueOrder>> getOrderByVerifyCode(@RequestParam String verifyCode) {
        List<GuiminYuyueOrder> list = guiminYuyueOrderService.list(new LambdaQueryWrapper<GuiminYuyueOrder>()
                .eq(GuiminYuyueOrder::getVerifyCode, verifyCode)
                .gt(GuiminYuyueOrder::getServiceDate, new Date())
                .eq(GuiminYuyueOrder::getState, GmYuyueOrderConstant.State.WAIT_USE.value));
        return R.ok(list);
    }

    /**
     * 使用订单
     *
     * @param request    h
     * @param orderId    预约id
     * @param verifyCode 核销码
     * @return r
     */
    @PutMapping("/use/order")
    public R<Boolean> useOrder(HttpServletRequest request, @RequestParam Integer orderId, @RequestParam String verifyCode) {
        LoginInfoDto login = userInfoApi.getLogin(request);
        int count = userInfoService.count(new LambdaQueryWrapper<UserInfo>()
                .select(UserInfo::getRole).eq(UserInfo::getId, login.getId())
                .nested(i -> i
                        .eq(UserInfo::getRole, UserConstant.Role.ADMIN.toString())
                        .or().eq(UserInfo::getRole, UserConstant.Role.ROOT.toString())));
        if (count < 0) {
            return R.failed("权限不足");
        }
        boolean update = guiminYuyueOrderService.update(new GuiminYuyueOrder()
                        .setState(GmYuyueOrderConstant.State.WAIT_EVALUATE.value).setVerifielId(login.getId()),
                new LambdaQueryWrapper<GuiminYuyueOrder>()
                        .eq(GuiminYuyueOrder::getId, orderId).eq(GuiminYuyueOrder::getVerifyCode, verifyCode));
        return update ? R.ok(null) : R.failed("核销失败");
    }

}

